<template>
    <div id="three-container">
        <div id="three-canvas"></div>
    </div>
</template>

<script>
    import * as THREE from 'three'
    import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
    import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'

    // 引擎装配的JSON数据
    import ENGINE_ASSEMBLY_JSON from './ENGINE ASSEMBL.json'

    export default {
        mounted() {
            this.initThree()
        },
        methods: {
            async initThree() {
                // 初始化场景
                const scene = new THREE.Scene();
                scene.background = new THREE.Color(0xf0f0f0);

                // 初始化相机
                const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
                // 调整相机初始位置和朝向
                camera.position.set(0, 0, 500); // 单位：米
                // camera.near = 0.01; // 能看见0.1mm的物体
                camera.far = 10000;   // 能看见10km外的物体
                camera.updateProjectionMatrix();

                // 初始化渲染器
                const renderer = new THREE.WebGLRenderer({ antialias: true });
                renderer.setSize(window.innerWidth, window.innerHeight);
                document.getElementById('three-canvas').appendChild(renderer.domElement);

                // 添加光源
                this.addLights(scene);

                // 添加1米长的坐标轴
                const axes = new THREE.AxesHelper(100);
                scene.add(axes);

                // 添加10cm网格地面
                const grid = new THREE.GridHelper(10, 10);
                scene.add(grid);

                // 初始化控制器
                const controls = new OrbitControls(camera, renderer.domElement);
                controls.enableDamping = true;

                // 加载并组装引擎
                await this.loadEngineAssembly(scene, camera, controls);

                // 动画循环
                const animate = () => {
                    requestAnimationFrame(animate);
                    controls.update();
                    renderer.render(scene, camera);
                };
                animate();

                // 窗口大小调整
                window.addEventListener('resize', () => {
                    camera.aspect = window.innerWidth / window.innerHeight;
                    camera.updateProjectionMatrix();
                    renderer.setSize(window.innerWidth, window.innerHeight);
                });
            },

            // 添加光源
            addLights(scene) {
                const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
                scene.add(ambientLight);

                const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
                directionalLight.position.set(1, 1, 1);
                scene.add(directionalLight);
            },

            // 加载并组装引擎
            async loadEngineAssembly(scene) {
                const loader = new GLTFLoader();

                // 先加载所有零件模型
                const parts = {
                    'CRANK SHAFT': await this.loadModel(loader, '/models/CRANK SHAFT.glb'),
                    'ENGINE BLOCK': await this.loadModel(loader, '/models/ENGINE BLOCK.glb'),
                    'Piston Head': await this.loadModel(loader, '/models/Piston Head.glb'),
                    'CONNECTING ROD': await this.loadModel(loader, '/models/CONNECTING ROD.glb'),
                    'ROD CAP': await this.loadModel(loader, '/models/ROD CAP.glb'),
                    'PISTON NPIN': await this.loadModel(loader, '/models/PISTON NPIN.glb')
                };

                // 创建容器组
                const engineGroup = new THREE.Group();
                scene.add(engineGroup);

                // 递归组装模型
                this.assembleModel(engineGroup, ENGINE_ASSEMBLY_JSON, parts);

                const box = new THREE.Box3().setFromObject(engineGroup);
                const center = box.getCenter(new THREE.Vector3());
                engineGroup.position.sub(center);
            },

            // 加载单个GLB模型
            loadModel(loader, url) {
                return new Promise((resolve, reject) => {
                    loader.load(
                        url,
                        (gltf) => resolve(gltf.scene.clone()),
                        undefined, // 进度回调
                        (error) => {
                            console.error('Error loading model:', url, error);
                            reject(error);
                        }
                    );
                });
            },

            // 递归组装模型
            assembleModel(parent, node, parts, inheritedMatrix = null) {
                console.group(`Processing node: ${node.name} (${node.type})`);

                // 1. 解析当前节点的变换矩阵
                const nodeMatrix = new THREE.Matrix4();
                if (node.position_arr) {
                    const arr = node.position_arr;
                    // 注意：CATIA使用行主序，Three.js使用列主序
                    // nodeMatrix.set(
                    //     arr[0], arr[3], arr[6], arr[9],  // 第一列
                    //     arr[1], arr[4], arr[7], arr[10], // 第二列
                    //     arr[2], arr[5], arr[8], arr[11], // 第三列
                    //     0,     0,     0,     1          // 第四列
                    // );
                    nodeMatrix.set(
                        arr[0], arr[1], arr[2], arr[9],
                        arr[3], arr[4], arr[5], arr[10],
                        arr[6], arr[7], arr[8], arr[11],
                        0, 0, 0, 1
                    );
                    console.log('Local matrix:', nodeMatrix);
                }

                // 2. 计算世界矩阵
                const worldMatrix = new THREE.Matrix4();
                if (inheritedMatrix) {
                    worldMatrix.multiplyMatrices(inheritedMatrix, nodeMatrix);
                } else {
                    worldMatrix.copy(nodeMatrix);
                }
                console.log('World matrix:', worldMatrix);

                if (node.type === 'CATPart' && parts[node.name]) {
                    // 3. 处理零件节点
                    const model = parts[node.name].clone(true);

                    // 重置原有变换（重要！）
                    model.position.set(0, 0, 0);
                    model.quaternion.set(0, 0, 0, 1);
                    model.scale.set(1000, 1000, 1000);

                    // 旋转零件
                    // model.rotation.x = Math.PI / 2;
                    model.quaternion.setFromAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI / 2);

                    // 应用完整的世界变换
                    model.applyMatrix4(nodeMatrix);

                    console.log('Model final position:', model.position);
                    console.log('Model final rotation:', model.rotation);
                    parent.add(model);
                }
                else if (node.type === 'CATProduct' && node.children) {
                    // 4. 处理装配体节点
                    const assemblyGroup = new THREE.Group();

                    // 应用装配体级别的变换
                    assemblyGroup.applyMatrix4(worldMatrix);

                    // 旋转二级装配体
                    assemblyGroup.quaternion.setFromAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI / 2);

                    // 递归处理子节点
                    node.children.forEach(child => {
                        this.assembleModel(assemblyGroup, child, parts, worldMatrix);
                    });

                    parent.add(assemblyGroup);
                    console.log('Assembly group position:', assemblyGroup.position);
                }
                const pathOrName = node.path || node.name
                console.log(`组装节点: ${pathOrName}`, {
                    position: new THREE.Vector3().setFromMatrixPosition(worldMatrix),
                    matrix: worldMatrix
                });
                console.groupEnd();
            }
        }
    }
</script>

<style scoped>
    #three-container {
        position: relative;
        width: 100%;
        height: 100vh;
    }

    #three-canvas {
        width: 100%;
        height: 100%;
    }
</style>